/**
 * Baijiahulian.com Inc. Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.baijia.dao.impl;

import com.baijia.dao.UserDao;
import com.baijia.dao.po.User;

import com.mysql.jdbc.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @title UserDaoImpl
 * @desc TODO
 * @author macrohuang
 * @date Jan 20, 2016
 * @version 1.0
 */
@Repository
public class UserDaoImpl extends CommonDaoImpl<User, Long> implements UserDao {

    @Autowired
    @Qualifier("namedParameterJdbcTemplate")
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private String selectSql =
        "select id,number,name,mobile,login_password as password,email,status,mobile_verify as mobileVerify"
            + ",email_verify as emailVerify from cdb.user ";

    public UserDaoImpl() {
        super(User.class);
    }

    @Override
    public User getUserByMobile(String mobile) throws DataAccessException {
        List<User> list =
            jdbcTemplate.query(
                "select id,number,name,mobile,login_password as password,email,status from cdb.user where mobile=?",
                new BeanPropertyRowMapper<>(User.class), new Object[] { mobile });
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    private static String INSERT_USER =
        "insert into cdb.user(mobile,login_password,name,email,number,mobile_verify,created_at) values(?,?,?,?,0,1,now())";

    @Override
    public long save(final User user) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(INSERT_USER, Statement.RETURN_GENERATED_KEYS);
                int index = 0;
                ps.setString(++index, user.getMobile());
                ps.setString(++index, user.getPassword());
                ps.setString(++index, user.getName());
                ps.setString(++index, user.getEmail());
                return ps;
            }
        }, keyHolder);

        long autoIncId = keyHolder.getKey().longValue();

        return autoIncId;
    }

    @Override
    public int updateNumber(long lastInsertId, long number) {
        return jdbcTemplate
            .update("update cdb.user set number = ? where id = ?", new Object[] { number, lastInsertId });
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update(
            "update cdb.user set mobile=?,name=?,email=?,login_password=?,"
                + "mobile_verify=?,email_verify=?,status=? where id = ?",
            new Object[] { user.getMobile(), user.getName(), user.getEmail(), user.getPassword(),
                user.getMobileVerify(), user.getEmailVerify(), user.getStatus(), user.getId() });
    }

    @Override
    public int updateMobileById(String mobile, Long userId) {
        return jdbcTemplate.update("update cdb.user set mobile = ?, mobile_verify=1 where id = ?", new Object[] {
            mobile, userId });
    }

    @Override
    protected String selectSql() {
        return selectSql;
    }

    @Override
    public long getIdByNumber(Long number) {
        if (number != null && number > 0) {
            return jdbcTemplate.queryForObject("select id from cdb.user where number=? ", new Object[] { number },
                Long.class);
        }

        return 0;
    }

    public int updatePwdByMobile(String mobile, String password) {
        return jdbcTemplate.update("update cdb.user set login_password=? where mobile=?", new Object[] { password,
            mobile });
    }

}